package com.wang.ddp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.wang.ddp.dto.UserDTO;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wjh
 * @create 2023-04-19
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    //因为这个类是我们自己创建的拦截器，拦截器是在spring容器创建前就执行的，所以不会被spring容器管理，所以这个类的属性不会被自动注入
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取token
        String token = request.getHeader("authorization");
        if(Strings.isEmpty(token)){
            return true;
        }
        //2、从redis中获取用户信息
        String key = "login:token:"+token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        //判断map是否为null
        if (userMap.isEmpty()){
            return true;
        }
        //3、将map集合转为UserDTO，因为我们存入的时候是将UserDTO转为HashMap
        UserDTO userDTO = new UserDTO();
        BeanUtil.fillBeanWithMap(userMap,userDTO,false);
        //4、判断用户是否为空
        if (userDTO==null){
            return true;
        }

        //5、存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //6、更新token在Redis中的存活时间
        stringRedisTemplate.expire(key, 30L, TimeUnit.MINUTES);
        //7、放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
